﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Common;
using log4net;
using SqlSugar;
using AutoFacUtils;
using CashFlow.ShopManage.Def;
using CashFlow.Db.DAL;
using CashFlow.Db.Entity;
using CashFlow.Db.Repository;
using CashFlow.ShopManage.Service;
using CashFlow.ShopManage.Common;

namespace CashFlow.ShopManage.Service.Implement
{
    public class OrderService : Service<OrderEntity>, IOrderService
    {
        private IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }
        private IAdminService GetAdminService() { return AutoFacHelper.Get<IAdminService>(); }

        public IList<OrderBuySellInfo> QueryShopAllUsersOrder(int shopManagerUserId
            , string orderNo
            , string date
            , int? state
            , string buyer
            , string seller)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var query = db.Queryable<OrderEntity>()
                              .InnerJoin<UserInfoEntity>((o, b) => o.BuyerUserId == b.Id)
                              .InnerJoin<UserInfoEntity>((o, b, s) => o.SellerUserId == s.Id)
                              .InnerJoin<ShopUserEntity>((o, b, s, su) => o.BuyerUserId == su.UserId)
                              .Where((o, b, s, su) => su.ShopManagerUserId == shopManagerUserId);

                if (!string.IsNullOrEmpty(orderNo))
                {
                    query = query.Where((o, b, s, su) => o.OrderNo.Contains(orderNo));
                }
                if (!string.IsNullOrEmpty(date))
                {
                    query = query.Where((o, b, s, su) => o.CreateTime.ToString("yyyy-MM-dd") == date);
                }
                if (state.HasValue)
                {
                    query = query.Where((o, b, s, su) => o.State == state);
                }
                if (!string.IsNullOrEmpty(buyer))
                {
                    query = query.Where((o, b, s, su) => b.Name.Contains(buyer));
                }
                if (!string.IsNullOrEmpty(seller))
                {
                    query = query.Where((o, b, s, su) => s.Name.Contains(seller));
                }

                var ls = query.Select((o, b, s, su) => new OrderBuySellInfo
                {
                    Order = o,
                    Buyer = b,
                    Seller = s
                }).ToList();

                return ls;
            }
        }

        public IList<OrderAndUserInfo> QueryShopAllUsersOrder2(int shopManagerUserId
            , string date)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<OrderEntity>()
                           .InnerJoin<UserInfoEntity>((o, u) => o.BuyerUserId == u.Id)
                           .InnerJoin<ShopUserEntity>((o, u, su) => o.BuyerUserId == su.UserId)
                           .Where((o, u, su) => o.CreateTime.ToString("yyyy-MM-dd") == date
                                && su.ShopManagerUserId == shopManagerUserId)
                           .Select((o, u) => new OrderAndUserInfo
                           {
                               OrderInfo = o,
                               UserInfo = u
                           })
                           .ToList();
                return ls;
            }
        }

        public bool IsExistOrderIdInShop(int shopManagerUserId
            , int orderId
            , string date)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                int n = db.Queryable<OrderEntity>()
                          .InnerJoin<ShopUserEntity>((o, su) => o.BuyerUserId == su.UserId
                            || o.SellerUserId == su.UserId)
                          .Where((o, su) => o.CreateTime.ToString("yyyy-MM-dd") == date
                                && o.Id == orderId
                                && su.ShopManagerUserId == shopManagerUserId)
                          .Count();
                return n > 0;
            }
        }

        public ECreateOrderResult AddOrder(int buyerUserId
            , int sellerUserId
            , decimal amount)
        {
            var result = ECreateOrderResult.Other;

            string date = DateTime.Now.ToString("yyyy-MM-dd");
            using (var db = SqlSugarHelper.GetDb())
            {
                int n = db.Queryable<OrderEntity>()
                          .Where(x => x.BuyerUserId == buyerUserId
                                && x.CreateTime.ToString("yyyy-MM-dd") == date)
                          .Count();
                if (n > 0)
                {
                    result = ECreateOrderResult.RepeatBuyer;
                }
                else
                {
                    var entity = new OrderEntity
                    {
                        Amount = amount,
                        BuyerUserId = buyerUserId,
                        SellerUserId = sellerUserId,
                        CreateTime = DateTime.Now,
                        Name = MyCommonTool.GetProductName(),
                        OrderNo = MyCommonTool.CreateOrderNo(),
                        State = 0,
                        Visible = 0
                    };
                    int n2 = db.Insertable(entity).ExecuteCommand();
                    if (n2 > 0)
                    {
                        result = ECreateOrderResult.Success;
                    }
                }
            }

            return result;
        }

        public bool ReleaseOrder(string date)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var entity = new OrderEntity();
                entity.Visible = 1;
                int n = db.Updateable(entity)
                          .UpdateColumns(x => x.Visible)
                          .Where(x => x.CreateTime.ToString("yyyy-MM-dd") == date)
                          .ExecuteCommand();
                return n > 0;
            }
        }

        public EUpdateOrderResult UpdateOrder(int orderId
            , int buyerUserId
            , int sellerUserId
            , decimal amount
            , string date)
        {
            var result = EUpdateOrderResult.Other;

            using (var db = SqlSugarHelper.GetDb())
            {
                int n = db.Queryable<OrderEntity>()
                          .Where(x => x.BuyerUserId == buyerUserId
                                && x.Id != orderId
                                && x.CreateTime.ToString("yyyy-MM-dd") == date)
                          .Count();
                if (n > 0)
                {
                    result = EUpdateOrderResult.RepeatBuyer;
                }
                else
                {
                    var entity = new OrderEntity();
                    entity.Id = orderId;
                    db.Tracking(entity);
                    entity.BuyerUserId = buyerUserId;
                    entity.SellerUserId = sellerUserId;
                    entity.Amount = amount;
                    int n2 = db.Updateable(entity).ExecuteCommand();
                    if (n2 > 0)
                    {
                        result = EUpdateOrderResult.Success;
                    }
                }
            }

            return result;
        }
    }
}
